import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import {
  Tree,
  Icon,
  Skeleton,
  Modal,
  message,
  Empty,
  Form,
  Tag,
  Input,
  Select,
  Descriptions,
} from 'antd';
// import cloneDeep from 'lodash/cloneDeep';
import classNames from 'classnames';
import ScrollBar from '@/components/ScrollBar';
import SlickTable from '@/components/SlickTable';
import request from '@/utils/request';
import styles from '../index.less';
import Ikon from '@/components/Ikon';

const { TreeNode } = Tree;
const { Option } = Select;

function ViewPlanRule({ size, visiable, close, passId }) {
  // 组织树数据
  const [TreeData, setTreeData] = useState([]);
  // 选中点击的值
  const [selectedKeysArr, setSelectedKeysArr] = useState(['']);
  // 初始化加载组织树loading
  const [loading, setLoading] = useState(false);
  const [rightLoading, setRightLoading] = useState(false);
  // 右边区域数据
  const [ruleData, setRuleData] = useState({});
  const [result, setResult] = useState([]);
  // 规则设置内容
  const [text, setText] = useState('');
  // 方案类型还是规则类型
  const [type, setType] = useState('');

  // 转换规则设置的内容预览
  const changePreLog = value => {
    let chageValue = '';
    switch (value) {
      case '||':
        chageValue = 'OR';
        break;
      case '&&':
        chageValue = 'AND';
        break;
      default:
        break;
    }
    return chageValue;
  };

  const changeOptType = value => {
    const data = result.filter(function(item) {
      return item.attrValue === value;
    });
    return data[0].attrValueName;
  };

  const changeRuleSet = data => {
    let text = '';
    data.forEach((data1, index) => {
      let configValue = '';
      data1.map(item => {
        configValue = `${configValue}${configValue === '' ? '' : '、'}${
          item.attrValueName ? item.attrValueName : item.attrValue
        }`;
      });

      const curText = `${data1[0].leftBrackets ? data1[0].leftBrackets : ''}{${
        data1[0].attr.objName
      }.${data1[0].attr.attrName ? data1[0].attr.attrName : data1[0].attr.attrCode}$${changeOptType(
        data1[0].optType
      )}${configValue}}${data1[0].rightBrackets ? data1[0].rightBrackets : ''}${
        data.length - 1 !== index ? changePreLog(data1[0].preLog) : ''
      }`;
      const nextText = `${text}${curText}`;
      text = nextText;
    });
    setText(text);
  };

  // 初始化查询
  async function query() {
    let result1;
    await Promise.all([
      request('pmc/pms/PmOrderFlowNodeController/queryTachePlanTree', {
        data: {
          flowNodeId: passId,
        },
      }),
      request('pmc/pms/StaticDataController/batchQueryStaticAttr.do', {
        data: ['RULE_COND_COMBOBOX'],
      }),
    ]).then(res => {
      result1 = res;
    });
    return result1;
  }

  // 初始化获取接口的Tree集合
  const queryTreeData = () => {
    setLoading(true);
    query()
      .then(res => {
        if (res[0].success && res[1].success) {
          setTreeData(res[0].data);
          setResult(res[1].data.RULE_COND_COMBOBOX);
        } else {
          message.error('接口请求有误！请检查');
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 查询右边对应规则的数据信息
  const queryPlanRule = (id, type) => {
    if (type === 'rule') {
      setRightLoading(true);
      request('pmc/pms/RuleCfgController/showRuleCond', {
        data: {
          ruleId: id,
        },
      })
        .then(res => {
          if (res.success) {
            setRuleData(res.data);
            changeRuleSet(res.data.ruleCondList ? res.data.ruleCondList : []);
          } else {
            message.error(res.errMessage);
          }
        })
        .always(() => {
          setRightLoading(false);
        });
    } else {
      setRightLoading(true);
      request('pmc/pms/RuleCfgController/findRulesByPlan', {
        data: {
          planId: id,
        },
      })
        .then(res => {
          if (res.success) {
            setRuleData(res.data);
          } else {
            message.error(res.errMessage);
          }
        })
        .always(() => {
          setRightLoading(false);
        });
    }
  };

  useEffect(() => {
    queryTreeData();
  }, []);

  // 遍历递归集合数据，渲染组织树
  const renderTreeNode = TreeArr => {
    if (TreeArr.length > 0) {
      return TreeArr.map(item => {
        return (
          <TreeNode
            icon={({ expanded }) => (
              /* eslint-disable */
              <Icon
                type={
                  expanded
                    ? item.children && item.children.length > 0
                      ? 'folder-open'
                      : 'file'
                    : item.children && item.children.length > 0
                    ? 'folder'
                    : 'file'
                }
              />
              /* eslint-enable */
            )}
            title={`${item.name}(${item.typeName ? item.typeName : ''})`}
            key={`${item.id}_${item.type}_${item.treeId}`}
            isLeaf={item.children && item.children.length > 0 ? false : true}
            // 往组织树挂一个detaRef 可供外部获取选中的整个对象数据
            dataRef={item}
          >
            {item.children ? renderTreeNode(item.children) : null}
          </TreeNode>
        );
      });
    }
  };

  // 选中节点
  const selectTreeNode = selectedKeys => {
    /* eslint-disable */
    let type;
    let id;
    selectedKeys.length > 0
      ? (setSelectedKeysArr(selectedKeys),
        (type = selectedKeys[0].match(/(\S*)_/)[1].match(/_(\S*)/)[1]),
        (id = selectedKeys[0].match(/(\S*)_/)[1].match(/(\S*)_/)[1]))
      : (setSelectedKeysArr(selectedKeysArr),
        (type = selectedKeysArr[0].match(/(\S*)_/)[1].match(/_(\S*)/)[1]),
        (id = selectedKeysArr[0].match(/(\S*)_/)[1].match(/(\S*)_/)[1]));
    setType(type);
    queryPlanRule(id, type);
  };

  return (
    <Modal
      title="规则详情"
      width="800px"
      destroyOnClose
      visible={visiable}
      okText="保存"
      footer={null}
      onCancel={close}
    >
      <Skeleton active loading={loading}>
        {TreeData.length > 0 ? (
          <div className={styles.scroll_main}>
            <div className={styles.scroll_left}>
              <ScrollBar autoHide autoHeight autoHeightMax={size.height * 0.6}>
                <div style={{ height: size.height * 0.6, paddingRight: '8px' }}>
                  <Tree showIcon onSelect={selectTreeNode} selectedKeys={selectedKeysArr}>
                    {renderTreeNode(TreeData)}
                  </Tree>
                </div>
              </ScrollBar>
            </div>

            <div
              className={styles.scroll_content}
              style={{ paddingLeft: '16px', borderLeft: '1px solid #e8e8e8' }}
            >
              <ScrollBar autoHide autoHeight autoHeightMax={size.height * 0.6}>
                <div
                  style={{ height: size.height * 0.6, margin: 0 }}
                  className={styles.set_conditionright}
                >
                  <Skeleton active loading={rightLoading}>
                    {type === 'plan' ? (
                      Array.isArray(ruleData) && ruleData.length ? (
                        <SlickTable
                          rowKey={record => record.ruleId}
                          columns={[
                            {
                              title: '规则编码',
                              dataIndex: 'ruleId',
                              ellipsis: true,
                            },

                            {
                              title: '规则名称',
                              dataIndex: 'ruleName',
                              ellipsis: true,
                            },
                            {
                              title: '优先级',
                              dataIndex: 'priority',
                              ellipsis: true,
                            },
                            {
                              title: '规则关系',
                              dataIndex: 'relType',
                              ellipsis: true,
                              render: (text, record) => {
                                return text === '0'
                                  ? `并行`
                                  : text === '1'
                                  ? '依赖'
                                  : text === '2'
                                  ? '互斥'
                                  : '全部互斥';
                              },
                            },
                            {
                              title: '关系值',
                              dataIndex: 'relyonRuleId',
                              ellipsis: true,
                            },
                          ]}
                          pagination={false}
                          dataSource={ruleData}
                        />
                      ) : (
                        <Ikon status="404" subTitle="抱歉，暂无数据展示 ~" />
                      )
                    ) : Object.keys(ruleData).length === 0 ||
                      (ruleData.ruleCondList &&
                        Object.keys(ruleData.ruleCO).length === 0 &&
                        ruleData.ruleCondList.length === 0 &&
                        ruleData.ruleConstList &&
                        ruleData.ruleConstList.length === 0) ? (
                      <Ikon status="404" subTitle="抱歉，暂无数据展示 ~" />
                    ) : (
                      <>
                        {/* <div className="ant-detail-title">
                          <span className="padding-right">组件设置</span>
                        </div>
                        <div className={styles.rule_form}>
                          {ruleData.ruleCondList && ruleData.ruleCondList.length > 0 ? (
                            ruleData.ruleCondList.map((tag, index) => (
                              <div>
                                <div className={styles.rule_title}>
                                  {tag[0].attr.attrId ? tag[0].attr.attrName : tag[0].attr.attrCode}
                                </div>
                                <div>
                                  <Select
                                    style={{ width: 150 }}
                                    placeholder="请选择"
                                    value={tag[0].optType}
                                    disabled
                                  >
                                    {result.map(item => {
                                      return (
                                        <Option key={item.attrValue} value={item.attrValue}>
                                          {item.attrValueName}
                                        </Option>
                                      );
                                    })}
                                  </Select>
                                  <span className={classNames(styles.rule_tag)}>
                                    {tag.map(i => (
                                      <Tag key={i.attrValue}>
                                        {i.attrValueName ? i.attrValueName : i.attrValue}
                                      </Tag>
                                    ))}
                                  </span>
                                </div>
                              </div>
                            ))
                          ) : (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                          )}
                        </div> */}

                        <div className="ant-detail-title">
                          <span className="padding-right">组件设置</span>
                        </div>
                        <Descriptions column={2}>
                          <Descriptions.Item label="组件设置">
                            {ruleData.ruleCO ? ruleData.ruleCO.assName : '暂无'}
                          </Descriptions.Item>
                          <Descriptions.Item label="入参转换组件">
                            {ruleData.ruleCO ? ruleData.ruleCO.transAssName : '暂无'}
                          </Descriptions.Item>
                        </Descriptions>
                        <div className="ant-detail-title">
                          <span className="padding-right">条件预览</span>
                        </div>
                        {text ? (
                          <div className="padding-right">
                            <Input.TextArea value={text} rows={4} disabled />
                          </div>
                        ) : (
                          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        )}

                        <div className="ant-detail-title">
                          <span className="padding-right">结果设置</span>
                        </div>
                        <div className={styles.rule_form}>
                          {ruleData.ruleConstList && ruleData.ruleConstList.length > 0 ? (
                            ruleData.ruleConstList.map(tag => (
                              <>
                                <div className={styles.rule_title}>
                                  {tag[0].attr.attrId ? tag[0].attr.attrName : tag[0].attr.attrCode}
                                </div>
                                <div
                                  className={classNames(styles.rule_tag)}
                                  style={{ marginLeft: 0 }}
                                >
                                  {tag.map(i => (
                                    <Tag key={i.attrValue}>
                                      {i.attrValueName ? i.attrValueName : i.attrValue}
                                    </Tag>
                                  ))}
                                </div>
                              </>
                            ))
                          ) : (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                          )}
                        </div>
                      </>
                    )}
                  </Skeleton>
                </div>
              </ScrollBar>
            </div>
          </div>
        ) : (
          <Empty description="暂无数据节点" image={Empty.PRESENTED_IMAGE_SIMPLE} />
        )}
      </Skeleton>
    </Modal>
  );
}

export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(ViewPlanRule));
